package com.haixee.parkdemo.common.response;

import com.haixee.parkdemo.common.context.WebContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * AOP: 记录正常返回结果
 *
 * @author RUIFENG GUO
 * 2020/3/26 11:58
 */
@Component
@Aspect
@Slf4j
public class ControllerNormalHandler {

    @Autowired(required = false)
    private List<ConPostProcessor> processors;

    @Autowired(required = false)
    private List<ConPreProcessor> preProcessors;

    @Pointcut("execution(* com.haixee.*.*.controller.*.* (..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object afterPointCut(ProceedingJoinPoint pjp) throws Throwable {

        if (preProcessors != null && preProcessors.size() != 0) {
            for (ConPreProcessor processor : preProcessors) {
                processor.process(pjp);
            }
        }

        // 方法执行
        Object result = pjp.proceed();

        if (result instanceof ResResult) {
            // 发布 controller 正常事件
            ResResult r = (ResResult) result;

            if (processors != null && processors.size() != 0) {
                MethodSignature signature = (MethodSignature) pjp.getSignature();
                for (ConPostProcessor processor : processors) {
                    processor.process(r, signature);
                }
            }

            WebContextHolder.setResponseCode(r.getCode());
            WebContextHolder.setResponseMsg(r.getMsg());
        }

        return result;
    }

}
